package com.github.tommas.admintpl.controller;

import com.github.tommas.admintpl.bean.model.Role;
import com.github.tommas.admintpl.bean.vo.AssignedPermission;
import com.github.tommas.admintpl.bean.vo.PaginationQuery;
import com.github.tommas.admintpl.bean.vo.PermissionInfo;
import com.github.tommas.admintpl.bean.vo.SearchRoleParam;
import com.github.tommas.admintpl.common.CommonResult;
import com.github.tommas.admintpl.common.CommonResultCode;
import com.github.tommas.admintpl.common.PaginationData;
import com.github.tommas.admintpl.security.permission.Permissions;
import com.github.tommas.admintpl.service.RoleService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/role")
public class RoleController implements RequirePermissionController {
    @Autowired
    RoleService roleService;

    @RequiresPermissions(Permissions.ROLE_READ)
    @PostMapping("/list")
    public CommonResult<PaginationData<Role>> getRoleList(@RequestBody PaginationQuery<SearchRoleParam> pq) {
        return CommonResult.success(roleService.getRoleList(pq));
    }

    @RequiresPermissions(Permissions.ROLE_CREATE)
    @PostMapping("/create")
    public CommonResult<Role> createRole(@RequestBody Role role) {
        return CommonResult.success(roleService.createRole(role));
    }

    @RequiresPermissions(Permissions.ROLE_EDIT)
    @PostMapping("/update/{id}")
    public CommonResult<Role> updateRole(@PathVariable Integer id, @RequestBody Role role) {
        role = roleService.updateRole(id, role);
        if (role == null) {
            return new CommonResult<Role>(
                    CommonResultCode.CONCURRENT_WRITE.getCode(), CommonResultCode.CONCURRENT_WRITE.getMessage(), null);
        }

        return CommonResult.success(role);
    }

    @RequiresPermissions(Permissions.ROLE_DELETE)
    @PostMapping("/delete/{id}")
    public CommonResult deleteRole(@PathVariable Integer id) {
        boolean result = roleService.deleteRole(id);
        if (!result) {
            return CommonResult.failed("Delete role failed", null);
        }

        return CommonResult.success();
    }

    @RequiresPermissions(Permissions.ROLE_ASSIGN_PERMISSION)
    @GetMapping("/permissions")
    public CommonResult<List<PermissionInfo>> getPermissions() {
        return CommonResult.success(roleService.getPermissions());
    }

    @RequiresPermissions(Permissions.ROLE_ASSIGN_PERMISSION)
    @PostMapping("/assign-permission/{roleId}")
    public CommonResult assignPermission(@PathVariable Integer roleId, @RequestBody List<AssignedPermission> permissions) {
        if (!permissions.isEmpty()) {
            roleService.assignRolePermission(roleId, permissions);
        }
        return CommonResult.success();
    }
}
